<?php

namespace app\commission;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductSku;
use app\redis\Cache;
use app\redis\Key;

class Stock
{
    private $order;

    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    public function run()
    {
        $item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        // var_dump($item);exit;

        foreach ($item as $v) {
            if ($v->product_id > 0) {
                $product = Product::findOne(['id' => $v->product_id]);
                $product->stock -= $v->quantity;
                $product->save();

                // redis
                Cache::delete(Key::$PRODUCT_DETAIL . $product->id);
            }
            if ($v->product_sku_id > 0) {
                $sku = ProductSku::findOne(['id' => $v->product_sku_id]);
                $sku->stock -= $v->quantity;
                $sku->save();
            }


        }
    }
}